﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using Htss.Platform.Data;
using System.Reflection;
using System.ComponentModel;
namespace Htss.Platform.Web
{
    public static class ModelAssignment
    {
        /// <summary>
        /// 实体赋值(根据请求的表单)
        /// </summary>
        /// <param name="Request"></param>
        /// <param name="Model"></param>
        public static void SetModel(HttpRequestBase Request,BasicModel Model)
        {
            Type type = Model.GetType();

            //处理实体类属性
            PropertyInfo[] proInfo = type.GetProperties();
            foreach (PropertyInfo pro in proInfo)
            {
                if (Request.Form[pro.Name]!=null)
                {
                    pro.SetValue(Model, Change(Request.Form[pro.Name],pro.PropertyType), null);        
                }
            }
        }
        /// <summary>
        /// 类型转换
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static object Change(object value,Type type)
        {
            if (type.IsValueType)
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    if (value == null)
                    {
                        return null;
                    }
                    NullableConverter nullableConverter = new NullableConverter(type);
                    value=  Convert.ChangeType(value,nullableConverter.UnderlyingType);
                }
            }
            return value;
        }
    }
}
